<template>
  <div class="kbpContainer">
    <el-row :span="24" style="margin-bottom: 15px;">
      <el-col :span="2" style="width: 35px;">
        <el-popover v-model="categoryPopover" placement="bottom" trigger="click">
          <el-input v-model="knowFilterText" type="text" placeholder @input="KnowFilterChange" />
          <el-scrollbar class="knowBrowse_tree_scrollBar">
            <el-tree
              ref="knowTree"
              class="knowBrowse_tree"
              :data="knowBrowseTreeData"
              :props="knowBrowseProps"
              node-key="id"
              :highlight-current="true"
              :expand-on-click-node="false"
              :filter-node-method="knowFilterNode"
              @node-click="knowBrowseClick"
            >
              <!--<span class="custom-tree-node" style="padding: 5px" slot-scope="{ node, data }">-->
              <!--<span style="width: 175px;overflow-x: auto">{{ node.label }}</span>-->
              <!--</span>-->
            </el-tree>
          </el-scrollbar>
          <i
            slot="reference"
            class="iconliebiao iconfont"
            style="font-size: 28px;cursor: pointer;"
            title="知识目录"
          />
          <!--          <i slot="reference" class="el-icon-s-operation popoverIcon" title="知识目录"></i>-->
        </el-popover>
      </el-col>
      <el-col :span="22" style="width: calc(100% - 40px);">
        <el-autocomplete
          v-model="tableKeyWord"
          class="inline-input"
          :fetch-suggestions="queryHotSearch"
          :debounce="0"
          placeholder="请输入内容"
          clearable
          size="small"
          style="width: 50%"
          @select="handleSelect"
          @keydown.enter.native="tableSearch(!permission.workbenchKbpIntelligentSearch)"
        ></el-autocomplete>
        <el-button
          v-if="permission.workbenchKbpIntelligentSearch && permission.aiSwitch"
          style="margin: 0px 4px;"
          type="primary"
          @click="tableSearch(false)"
        >智能搜索</el-button>
        <el-button
          v-if="permission.workbenchKbpSearch"
          style="margin: 0px 0px;"
          type="primary"
          @click="tableSearch(true)"
        >搜索</el-button>
        <el-button style="margin-left: 4px;" type="primary"
          v-if="permission.workbenchKbpIntelligentSearch && permission.aiSwitch"
          @click="tableGlobalSearch">全量搜索</el-button>
        <el-button
          v-if="permission.workbenchKbpListAsk"
          style="margin: 0px 4px;"
          type="primary"
          @click="questionClick"
        >提问</el-button>
      </el-col>
    </el-row>
    <el-row>
      <!-- 知识库列表 -->
      <el-row v-show="categoryName != businessCategory">
        <el-table :data="tableData" :height="tableHeight" style="width: 100%;">
          <el-table-column min-width="100" prop="title" label="标题">
            <template slot-scope="scope">
              <span
                class="hideText"
                style="cursor: pointer"
                :title="scope.row.title"
                @click="toDetail(scope.row)"
              >
                <i
                  v-if="scope.row.topStatus == 1"
                  class="el-icon-star-on"
                  style="color: #409EFF;font-size: 15px;"
                />
                {{ scope.row.title }}
              </span>
            </template>
          </el-table-column>
          <!--          <el-table-column-->
          <!--            prop="summary"-->
          <!--            label="摘要"-->
          <!--            min-width="200">-->
          <!--            <template slot-scope="scope">-->
          <!--              <div :title="scope.row.summary">-->
          <!--                <div class="high-title hideText">{{ scope.row.summary }}</div>-->
          <!--              </div>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column width="170" prop="updateTime" label="更新日期" />
        </el-table>
      </el-row>
      <el-row v-show="categoryName == businessCategory">
        <el-table :data="tableData" :height="tableHeight" style="width: 100%;">
          <el-table-column prop="type" label="业务类型名称" />
          <el-table-column
            v-if="knowledgeParentName == outCategory"
            prop="clickCountOutOut"
            label="外部点击数"
            width="120"
          />
          <el-table-column
            v-else-if="knowledgeParentName == inCategory"
            prop="clickCountOutIn"
            label="外部点击数"
            width="120"
          />
          <el-table-column
            v-else-if="knowledgeParentName == wendaCategory"
            prop="clickCountOutQues"
            label="外部点击数"
            width="120"
          />
          <el-table-column
            v-if="knowledgeParentName == outCategory"
            prop="clickCountInOut"
            label="内部点击数"
            width="120"
          />
          <el-table-column
            v-else-if="knowledgeParentName == inCategory"
            prop="clickCountInIn"
            label="内部点击数"
            width="120"
          />
          <el-table-column
            v-else-if="knowledgeParentName == wendaCategory"
            prop="clickCountInQues"
            label="内部点击数"
            width="120"
          />
        </el-table>
      </el-row>
      <!-- 相关搜索 -->
      <el-row v-if="isSuggest" style="margin-top: 13px;margin-bottom: 9px;">
        <el-card shadow="never" style="background-color: rgb(245, 245, 245);">
          <div style="height: 120px;">
            <div style="margin-left: 5px;height: 100%">
              <div class="title_span" style="font-size: 15px;font-weight: 400;">相关搜索</div>
              <div
                style="margin-top: 8px;display: flex;flex-wrap: wrap;width: 100%;align-content: space-evenly;height: 90%;"
              >
                <p
                  v-for="(s,index) in suggestList"
                  v-if="index < 8"
                  class="time_span"
                  style="color: rgb(64, 158, 255);margin-right:15px; cursor: pointer;"
                  @click="handleSelect(s)"
                >{{ s.value }}</p>
              </div>
            </div>
          </div>
        </el-card>
      </el-row>
      <el-row class="tabListPage">
        <el-pagination
          small
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :pager-count="7"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-row>
    <el-dialog
      title="知识提问"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisibleQuestion"
      append-to-body
      width="90%"
    >
      <el-form ref="myForm">
        <el-form-item label="业务类型" style="margin-bottom: 10px;">
          <el-select
            v-model="questionType"
            style="width: 100%;"
            filterable
            multiple
            placeholder="请选择业务类型"
          >
            <el-option
              v-for="(question,index) in questionOption"
              :key="index+'d'"
              :label="question.type"
              :value="question.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="margin-bottom" label="知识内容">
          <el-input
            v-model="questionContent"
            type="textarea"
            autosize="{ minRows: 1, maxRows: 3}"
            maxlength="80"
            placeholder="请填写您想知道答案的问题（最多80字）..."
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisibleQuestion = false">取 消</el-button>
        <el-button size="small" type="primary" @click="questionSubmit">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  knowBussinessTree,
  knowledgeList,
  aiSearch,
  aiServerPage,
  suggestSearch,
  getKnowledgeType,
  submitKnowledge,
  knowledgeListHome
} from "@/api/kbp";
import { mapGetters } from "vuex";

export default {
  name: "KnowBrowse",
  data() {
    return {
      knowBrowseTreeData: [],
      knowBrowseProps: {
        children: "children",
        label: "name"
      },
      knowFilterText: "",
      tableKeyWord: "",
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      // 总条数
      totalCount: 0,
      // 预存10条热门问题
      tenHotQuestion: [],
      // 当前目录
      activeNode: "",
      activeParentNode: "",
      // 相关搜索
      isSuggest: false,
      suggestList: [],
      // 常规检索
      generalSearch: false,
      categoryPopover: false,
      businessCategory: window.Settings.businessCategory,
      categoryName: null,
      knowledgeParentName: null,
      outCategory: "外部知识库",
      inCategory: "内部知识库",
      wendaCategory: "问答库",
      tableHeight: document.documentElement.clientHeight - 185,
      dialogFormVisibleQuestion: false,
      questionType: "",
      questionOption: [],
      questionContent: "",
      knowledgeHomeFlag: true
    };
  },
  created() {},
  mounted() {
    const self = this;
    self.initKnowTree();
    // 增加监听事件，窗口变化时得到高度
    window.addEventListener(
      "resize",
      function() {
        self.tableHeight = document.documentElement.clientHeight - 185;
      },
      false
    );
  },
  methods: {
    // 初始化知识列表
    initKnowList() {
      this.getKnowledgeList(true);
    },
    // 获取当前选中节点的参数
    knowBrowseClick(data, node) {
      console.log("click data is: " + JSON.stringify(data));
      this.isSuggest = false;
      this.categoryPopover = false;
      this.generalSearch = false;
      this.activeNode = data.id;
      this.activeParentNode = data.parentId == 0 ? data.id : data.parentId;
      this.categoryName = data.name;
      this.knowledgeParentName = data.parentName;
      this.currentPage = 1;
      this.tableKeyWord = "";
      this.initHotQuestion();
      this.getKnowledgeList(false);
    },
    /** ***************************** 树模糊搜索 **************************************/
    // 树列表模糊查询功能
    KnowFilterChange() {
      // 这里每当输入的数据有变化就触发原生的过滤节点这个函数
      this.$refs.knowTree.filter(this.knowFilterText);
    },
    // 节点过滤
    knowFilterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /** **************************** 获取知识树接口 ************************************/
    // 初始化知识树目录
    initKnowTree() {
      knowBussinessTree()
        .then(res => {
          console.log("response knowBussinessTree is: " + JSON.stringify(res));
          if (res && res.data && res.data.data) {
            const data = res.data.data;
            this.knowBrowseTreeData = this.getTrees(data, 0);
            this.$nextTick(() => {
              this.knowBrowseClick(this.knowBrowseTreeData[0], null);
              this.$refs.knowTree.setCurrentKey(this.knowBrowseTreeData[0].id);
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    getTrees(list, parentId) {
      const items = {};
      // 获取每个节点的直属子节点，*记住是直属，不是所有子节点
      for (let i = 0; i < list.length; i++) {
        if (
          list[i].name != "论坛问答" &&
          list[i].name != "最新" &&
          list[i].name != "最热"
        ) {
          list[i].label = list[i].name;
          let key = list[i].parentId;
          if (items[key]) {
            items[key].push(list[i]);
          } else {
            items[key] = [];
            items[key].push(list[i]);
          }
        }
      }
      return this.formatTree(items, parentId);
    },

    formatTree(items, parentId) {
      const result = [];
      if (!items[parentId]) {
        return result;
      }
      for (const t of items[parentId]) {
        t.children = this.formatTree(items, t.id);
        result.push(t);
      }
      return result;
    },
    /** ****************************  搜索建议初始化  ************************************/
    // 初始化热门问题
    initHotQuestion() {
      const params = {
        current: 1,
        size: 10,
        orderRule: 2,
        sortRule: 0,
        knowledgeCategoryId: this.activeNode,
        parentId: this.activeParentNode,
        categoryName: window.Settings.hotCategory,
        timeCheck: 1, // 有效期
        body:{}
      };
      knowledgeList(params)
        .then(res => {
          this.tenHotQuestion = [];
          for (let i = 0; i < res.data.data.pages.records.length; i++) {
            this.tenHotQuestion.push({
              value: res.data.data.pages.records[i].title,
              id: res.data.data.pages.records[i].id
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 搜索建议初始化,10个热门问题
    queryHotSearch(queryString, cb) {
      if (queryString) {
        if (this.permission.aiSwitch) {
          // 调用ai接口查询
          aiSearch({
            keyword: queryString,
            count: 10,
            knowledgeCategoryId: this.activeNode
          }).then(res => {
            cb(res.data.data);
          });
        } else {
          cb([]);
        }
      } else {
        this.tenHotQuestion.length > 0 ? cb(this.tenHotQuestion) : cb([])
      }
    },
    /** ****************************** 知识库列表相关 ************************************/
    // 知识库常见知识列表
    getKnowledgeList(flag) {
      this.knowledgeHomeFlag = true;
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        title: this.tableKeyWord,
        timeCheck: 1,
        // web父级id
        knowledgeCategoryId: this.activeNode,
        // ai父级id
        categoryIds: this.activeParentNode,
        parentId: this.activeParentNode,
        generalSearch: this.generalSearch ? "1" : "",
        body:{}
      };
      if (flag) {
        params.title = this.tableKeyWord;
      } else {
        params.title = "";
      }
      knowledgeList(params)
        .then(res => {
          if (res.data && res.data.data && res.data.data.pages.total) {
            this.tableData = res.data.data.pages.records;
            this.totalCount = res.data.data.pages.total;
          } else {
            this.tableData = [];
            this.totalCount = 0;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    aiInitTableData (title) {
      let data = {
        title: title || this.tableKeyWord,
        current: this.currentPage,
        size: this.pageSize,
        knowledgeCategoryId: this.activeNode,
        parentId: this.activeParentNode,
        categoryIds: this.activeParentNode,
      }
      aiServerPage(data).then(res => {
        if (res.data && res.data.pages) {
          this.tableData = res.data.pages.records || []
          this.totalCount = res.data.pages.total || 0
        }
      }).catch(error => {
        console.log(error)
        this.tableData = []
        this.totalCount = 0
      })
    },
    knowledgeListHome() {
      let params = {
        title: this.tableKeyWord,
        current: this.currentPage,
        size: this.pageSize
      }
      aiServerPage(params).then(res => {
        this.tableData = res.data.pages.records || []
        this.totalCount = res.data.pages.total || 0
      }).catch(error => {
        console.log(error)
        this.tableData = []
        this.totalCount = 0
      })
    },
    tableGlobalSearch() {
      // this.initHomeTableData();
      this.knowledgeListHome()
    },
    initHomeTableData() {
      this.knowledgeHomeFlag = false;
      let params = {
        title: this.tableKeyWord,
        current: this.currentPage,
        pageSize: this.pageSize
      };
      knowledgeListHome(params)
        .then(res => {
          this.tableData = res.data.data.records || [];
          this.totalCount = res.data.data.total || 0;
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 每页条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      if (this.knowledgeHomeFlag) {
        this.getKnowledgeList(true);
      } else {
        this.initHomeTableData();
      }
    },
    // 当前页数
    handleCurrentChange(val) {
      this.currentPage = val;
      if (this.knowledgeHomeFlag) {
        this.getKnowledgeList(true);
      } else {
        this.initHomeTableData();
      }
    },
    // 表格搜索
    tableSearch(flag) {
      this.isSuggest = false;
      this.generalSearch = flag;
      this.currentPage = 1;
      if (flag) {
        this.getKnowledgeList(true)
      } else {
        this.aiInitTableData(this.tableKeyWord)
      }
    },
    // 相关搜索查询
    handleSelect(item) {
      if (this.permission.aiSwitch) {
        this.suggestId = item.id;
        this.tableKeyWord = item.value;
        this.tableSearch(false);
        this.getSuggestSearch();
      }
    },
    // 相关推荐搜索接口
    getSuggestSearch() {
      const params = {
        size: this.pageSize,
        current: 1,
        title: this.tableKeyWord,
        timeCheck: 1,
        id: this.suggestId,
        orderRule: 2,
        sortRule: 0,
        knowledgeCategoryId: this.activeNode,
        categoryIds: this.activeParentNode,
        parentId: this.activeParentNode
      };
      suggestSearch(params)
        .then(res => {
          if (res.data.code == 200) {
            this.isSuggest = true;
            this.suggestList = res.data.data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    toDetail(obj) {
      sessionStorage.setItem("knowledgeId", obj.id);
      this.$router.push({
        path: "/kbpDetail",
        query: {
          id: obj.id,
          resourceType: obj.type,
        }
      });
      console.log("跳转详情页！！！");
    },
    /** ************************************ 提问相关 ******************************************/
    questionClick() {
      const that = this;
      const data = {
        current: 1,
        size: 999999999
      };
      getKnowledgeType(data)
        .then(res => {
          if (res.data && res.data.code == 200) {
            that.questionOption = res.data.data.records;
          }
        })
        .catch(err => {
          console.log(err);
        });
      that.dialogFormVisibleQuestion = true;
    },
    questionSubmit() {
      const that = this;
      if (that.questionType.length == 0) {
        that.$message({ message: "请选择业务类型！", type: "warning" });
        return;
      }
      if (!that.questionContent) {
        that.$message({ message: "请填写提问知识内容！", type: "warning" });
        return;
      }
      const data = {
        businessIds: that.questionType.join(),
        content: that.questionContent
      };
      submitKnowledge(data)
        .then(res => {
          console.log(JSON.stringify(res));
          if (res.data && res.data.code == 200) {
            that.questionType = "";
            that.questionContent = "";
            that.dialogFormVisibleQuestion = false;
            that.$message({
              message: "您的问题已提交成功，请耐心等待解答！",
              type: "success"
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  computed: {
    ...mapGetters(["permission"])
  },
  // 监听路由
  watch: {
    $route(to, from) {
      if (to.name == "kbp") {
        console.log("kbp index watch route!!!");
        this.initKnowList();
      }
    }
  }
};
</script>

<style scoped>
.knowBrowse_tree_scrollBar {
  width: 400px;
  height: 450px;
  padding-top: 10px;
}

.hideText {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.kbpContainer {
  width: 100%;
  height: 100%;
  padding: 10px 0px 10px 0px;
}

.popoverIcon {
  font-size: 33px;
  font-weight: 100;
  cursor: pointer;
}

.tabListPage {
  margin: 3px 5px;
  float: right;
}

.margin-right {
  margin-right: 10px;
}
</style>
